import React, { useState } from 'react';
import {
  Button,
  Table,
  Modal,
  Form,
  Select,
  Input,
  message,
  Card,
  Typography,
  Divider,
  Space,
  TreeSelect,
  Row,
  Col,
  Upload,
  DatePicker,
  Cascader,
} from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined, UploadOutlined } from '@ant-design/icons';
import { useModel, useNavigate } from '@umijs/max';
import condition from '@/components/staticFile/treeSelect.json';
import TextArea from 'antd/es/input/TextArea';
import 'react-quill/dist/quill.snow.css';
import ReactQuill from 'react-quill';
import { addService } from '@/services/apis/serviceProviderRegister';

const { Title } = Typography;
const COMMON_FIELD_STYLE = { width: '100%', height: 40, borderRadius: 4 };

// 定义表格数据类型
interface SceneData {
  key: string;
  industry: string;
  subIndustry: string;
  scene: string;
  sceneDesc: string;
}
const FORM_LAYOUT = {
  labelCol: { span: 6 }, // 调整标签宽度，避免长标签换行
  wrapperCol: { span: 18 },
  layout: 'horizontal' as const,
  
  size: 'middle' as const, // 统一表单控件尺寸
};
const ProductEnvironment: React.FC<{ form: any }> = (props) => {
  // 状态管理
  const [visible, setVisible] = useState(false); // 新增场景弹框是否可见
  const [form] = Form.useForm(); // 弹框表单
  const { stepProps, setStepProps } = useModel('PublishProduct.stepProps');
  const { initialState, setInitialState } = useModel('@@initialState');
  const navigate = useNavigate();

  const formFinished = () => {
    props.form.validateFields().then((values: any) => {
      addService({
        ...values,
        supplierId: (initialState?.currentUser as any).data.id,
        supplierName: (initialState?.currentUser as any).data.username,
      }).then(res => {
        const { code } = res;
        if (code == "0") {
          setStepProps(prev => ({ current: 0 }))
          props.form.resetFields()
          // //message.success("产品添加成功")
          navigate("/api_status_page", {
            state: {
              title: "服务商产品添加",
              message: "产品添加成功",
              callbackUrl: "/product_of_mine"
            }
          });
        }
      })
    })
  }
  const lastStep = () => {
    setStepProps((prev) => ({ ...prev, current: prev.current - 1 }));
  };

  const buildFullPathMap = (
    nodes: any[],
    parentPath: string[] = [],
    map: Record<string, string[]> = {},
  ) => {
    nodes.forEach((node) => {
      const currentPath = [...parentPath, node.title];
      map[node.value] = currentPath;
      if (node.children && node.children.length) {
        buildFullPathMap(node.children, currentPath, map);
      }
    });
    return map;
  };

  const fullPathMap = buildFullPathMap(condition);

  const convertNode = (node: any) => ({
    title: node.title,
    value: node.value,
    disabled: node.children && node.children.length > 0, // 非叶子节点禁用
    children: node.children?.map(convertNode),
  });

  return (
    // <Form
    //   {...FORM_LAYOUT}
    //   onFinish={onFinish}
    // >
    //   <div style={{ padding: 20, backgroundColor: '#f8f9fa', boxSizing: 'border-box' }}>
    //     <div
    //       style={{
    //         backgroundColor: '#fff',
    //         padding: 20,
    //         borderRadius: 8,
    //         boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
    //       }}
    //     >
    <>
      <div
        style={{
          fontSize: 16,
          fontWeight: 500,
          color: '#1f2937',
          marginBottom: 12,
        }}
      >
        使用场景
      </div>

      <Form.Item
        name="industry"
        label="所属行业"
        rules={[{ required: true, message: '请选择所属行业' }]}
      >
        <Select placeholder="请选择所属行业" style={{ width: '100%' }}>
          <Select.Option value="制造业">制造业</Select.Option>
          <Select.Option value="服务业">服务业</Select.Option>
          <Select.Option value="金融业">金融业</Select.Option>
          <Select.Option value="医疗健康">医疗健康</Select.Option>
          <Select.Option value="教育行业">教育行业</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item
        name="subIndustry"
        label="细分行业"
        rules={[{ required: true, message: '请选择细分行业' }]}
      >
        <Select mode="multiple" placeholder="请选择细分行业" style={{ width: '100%' }}>
          <Select.Option value="汽车制造">汽车制造</Select.Option>
          <Select.Option value="电子信息">电子信息</Select.Option>
          <Select.Option value="物流运输">物流运输</Select.Option>
          <Select.Option value="餐饮服务">餐饮服务</Select.Option>
          <Select.Option value="软件开发">软件开发</Select.Option>
        </Select>
      </Form.Item>

      <Form.List name="digitalContentList">
        {(fields, { add, remove }) => (
          <>
            {fields.map(({ key, name, ...restField }) => (
              <div
                key={key}
                style={{
                  marginBottom: 24,
                  borderBottom: '1px solid #e8e8e8',
                  paddingBottom: 16,
                }}
              >
                <Form.Item
                  {...restField}
                  label="场景"
                  name={[name, 'sceneName']}
                  rules={[{ required: true, message: '请选择场景' }]}
                  style={{ marginBottom: 20 }}
                >
                  <Cascader
                    allowClear
                    placeholder="请选择场景"
                    style={COMMON_FIELD_STYLE}
                    options={condition}
                    // treeDefaultExpandAll
                    fieldNames={{ label: 'title' }}
                    showSearch
                  // onChange={(value) => {
                  //   if (value) {
                  //     const fullPath = fullPathMap[value].join(' / ');
                  //     form.setFieldValue(['scenes', name, 'scene'], fullPath);
                  //   }
                  // }}
                  />
                </Form.Item>

                <Form.Item
                  {...restField}
                  label="场景描述"
                  name={[name, 'sceneDesc']}
                  rules={[{ required: true, message: '请输入场景描述' }]}
                  style={{ marginBottom: 20 }}
                >
                  <ReactQuill
                    theme="snow"
                    // value={value}
                    // onChange={setValue}
                    placeholder="请输入场景描述"
                    style={{
                      minHeight: 180,
                      background: '#fff',
                      borderRadius: 8,
                    }}
                    modules={{
                      toolbar: [
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ list: 'ordered' }, { list: 'bullet' }],
                        ['link', 'image'],
                        [{ align: [] }],
                        ['clean'],
                      ],
                    }}
                    className="custom-quill-editor"
                  />
                </Form.Item>
              </div>
            ))}

            <Form.Item wrapperCol={{ offset: 5, span: 19 }} style={{ marginTop: 40 }}>
              <Button type="dashed" onClick={() => add()} block>
                + 新增场景
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <Form.Item label={null} style={{ marginTop: 40, textAlign: 'center' }}>
        <Button style={{ marginRight: 10 }} onClick={lastStep} type="primary" >
          上一步
        </Button>
        <Button type="primary" onClick={formFinished}>
          完成
        </Button>
      </Form.Item>
    </>
    //     </div>
    //   </div>
    // </Form>
  );
};

export default ProductEnvironment;
